//
//  TestViewController3.m
//  MSDemo
//
//  Created by ms on 2023/2/20.
//

#import "TestViewController3.h"

@interface TestViewController3 ()
<
HXCustomNavigationControllerDelegate,
HXPhotoViewDelegate
>

@property (nonatomic, strong) UIImageView   *headView;
@property (nonatomic, strong) HXPhotoManager *manager;
@property (nonatomic, strong) HXPhotoModel  *photoModel;
@property (nonatomic, strong) NSURL *photoURL;

@end

@implementation TestViewController3

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"HXPhoto";
    
    _headView = ms_newImageView();
    [_headView ms_makeChains:^(MSChainMaker * _Nonnull make) {
        
        make
        .ms_backgroundColor(MS_HEX_COLOR(0xF7F7F7))
        .ms_addGestureRecognizer(UITapGestureRecognizer.new, self, @selector(previewPhoto))
        .ms_addGestureRecognizer(UILongPressGestureRecognizer.new, self, @selector(previewNetworkVideo))
        .ms_addToSuperView(self.view);
    }];
    _headView.image = [UIImage hx_imageNamed:@"hx_yundian_tupian"];
    
    [_headView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.navBar.mas_bottom).offset(50);
        make.centerX.equalTo(self.view);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(100);
    }];
    
    UIButton *photoPickerBtn = ms_newButton();
    
    [photoPickerBtn ms_makeChains:^(MSChainMaker * _Nonnull make) {
        
        make
        .ms_backgroundColor(UIColor.blackColor)
        .ms_title(@"选择照片", UIControlStateNormal)
        .ms_titleColor(UIColor.whiteColor, UIControlStateNormal)
        .ms_cornerRadii(10)
        .ms_addTarget(self, @selector(choosePhoto))
        .ms_addToSuperView(self.view);
    }];
    
    [photoPickerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(_headView.mas_bottom).offset(50);
        make.centerX.equalTo(_headView);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(30);
    }];
}


#pragma mark - event
/** 点击了“选择照片”按钮 */
- (void)choosePhoto
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"修改头像"
                                                                                 message:@""
                                                                          preferredStyle:UIAlertControllerStyleActionSheet];
        
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            [alertController addAction:[UIAlertAction actionWithTitle:@"拍照"
                                                                style:UIAlertActionStyleDefault
                                                              handler:^(UIAlertAction * _Nonnull action) {
                
                [self hx_presentCustomCameraViewControllerWithManager:self.manager
                                                                 done:^(HXPhotoModel *model, HXCustomCameraViewController *viewController) {
                    
                    NSSLog(@"done");
                    HXPhotoModel *photoModel = model;
                    [photoModel getImageWithSuccess:^(UIImage * _Nullable image, HXPhotoModel * _Nullable model, NSDictionary * _Nullable info) {
                        
                        self.headView.image = image;
                        self.photoModel = model;
                    }
                                        failed:^(NSDictionary * _Nullable info, HXPhotoModel * _Nullable model) {
                        
                        [self showHudWithMessage:@"选取照片失败"
                                            mode:MBProgressHUDModeText
                                        autoHide:YES];
                    }];
                }
                                                               cancel:^(HXCustomCameraViewController *viewController) {
                    
                    NSSLog(@"cancel");
                }];
            }]];
        }
        
        [alertController addAction:[UIAlertAction actionWithTitle:@"我的相册"
                                                            style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * _Nonnull action) {
            
            /*
             * 照片选择控制器方式一
            HXWeakSelf
            [self hx_presentSelectPhotoControllerWithManager:self.manager didDone:^(NSArray<HXPhotoModel *> *allList, NSArray<HXPhotoModel *> *photoList, NSArray<HXPhotoModel *> *videoList, BOOL isOriginal, UIViewController *viewController, HXPhotoManager *manager) {
                
                NSSLog(@"block - all - %@",allList);
                NSSLog(@"block - photo - %@",photoList);
                NSSLog(@"block - video - %@",videoList);
                if (!ms_arrayIsEmpty(photoList))
                {
                    HXPhotoModel *photoModel = photoList.firstObject;
                    [photoModel getImageWithSuccess:^(UIImage * _Nullable image, HXPhotoModel * _Nullable model, NSDictionary * _Nullable info) {
                        
                        weakSelf.headView.image = image;
                        weakSelf.photoModel = model;
                    }
                                             failed:^(NSDictionary * _Nullable info, HXPhotoModel * _Nullable model) {
                        
                        [weakSelf showHudWithMessage:@"选取照片失败"
                                                mode:MBProgressHUDModeText
                                            autoHide:YES];
                    }];
                }
                else if (!ms_arrayIsEmpty(videoList))
                {
                    HXPhotoModel *photoModel = videoList.firstObject;
                    // 获取当前资源图片
                    [photoModel getImageWithSuccess:^(UIImage * _Nullable image, HXPhotoModel * _Nullable model, NSDictionary * _Nullable info) {
                        
                        weakSelf.headView.image = image;
                        weakSelf.photoModel = model;
                    }
                                             failed:^(NSDictionary * _Nullable info, HXPhotoModel * _Nullable model) {
                        
                        [weakSelf showHudWithMessage:@"选取照片失败"
                                                mode:MBProgressHUDModeText
                                            autoHide:YES];
                    }];
                    
                    // 获取当前资源的URL
                    [photoModel getAssetURLWithVideoPresetName:AVAssetExportPresetMediumQuality
                                                       success:^(NSURL * _Nullable URL, HXPhotoModelMediaSubType mediaType, BOOL isNetwork, HXPhotoModel * _Nullable model) {
                        
                        // 导出成功
                        weakSelf.photoURL = URL;
                    }
                                                        failed:^(NSDictionary * _Nullable info, HXPhotoModel * _Nullable model) {
                        // 导出失败
                    }];
                }
            } cancel:^(UIViewController *viewController, HXPhotoManager *manager) {
                NSSLog(@"block - 取消了");
            }];
             */
            // 照片选择控制器方式二
            HXCustomNavigationController *nav = [[HXCustomNavigationController alloc] initWithManager:self.manager
                                                                                             delegate:self];
            [self presentViewController:nav animated:YES completion:nil];
        }]];
        
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消"
                                                            style:UIAlertActionStyleCancel
                                                          handler:nil]];
        
        [self presentViewController:alertController
                           animated:YES
                         completion:nil];
}
/** 点击了图片 */
- (void)previewPhoto
{
    HXWeakSelf
    if (self.photoModel)
    {
        [self showAlert:@"提示"
                message:@"是否编辑"
       messageAlignment:NSTextAlignmentCenter
             leftAction:[UIAlertAction actionWithTitle:@"编辑"
                                                 style:UIAlertActionStyleCancel
                                               handler:^(UIAlertAction * _Nonnull action) {
            
            HXPhotoEditConfiguration *configuration = self.manager.configuration.photoEditConfigur;
            if (self.photoModel.type == HXPhotoModelMediaTypeVideo || self.photoModel.type == HXPhotoModelMediaTypeCameraVideo)
            {
                //单独使用视频编辑功能
                [self hx_presentVideoEditViewControllerWithManager:self.manager
                                                        videoModel:self.photoModel
                                                          delegate:nil
                                                              done:^(HXPhotoModel *beforeModel,
                    HXPhotoModel *afterModel, HXVideoEditViewController *viewController) {
                    // beforeModel编辑之前、afterModel编辑之后
                    weakSelf.headView.image = afterModel.thumbPhoto;
                } cancel:^(HXVideoEditViewController *viewController) {
                    // 取消
                }];
            }
            else
            {
                // 单独使用仿微信编辑功能
                [self hx_presentWxPhotoEditViewControllerWithConfiguration:configuration photoModel:self.photoModel delegate:nil finish:^(HXPhotoEdit * _Nonnull photoEdit, HXPhotoModel * _Nonnull photoModel, HX_PhotoEditViewController * _Nonnull viewController) {
                    if (photoEdit) {
                        // 有编辑过
                        weakSelf.headView.image = photoEdit.editPreviewImage;
                    }else {
                        // 为空则未进行编辑
                        weakSelf.headView.image = photoModel.thumbPhoto;
                    }
                    // 记录下当前编辑的记录，再次编辑可在上一次基础上进行编辑
            //        weakSelf.photoEdit = photoEdit;
                } cancel:^(HX_PhotoEditViewController * _Nonnull viewController) {
                    // 取消
                }];
            }
        }]
            rightAction:[UIAlertAction actionWithTitle:@"放大"
                                                 style:UIAlertActionStyleDefault
                                               handler:^(UIAlertAction * _Nonnull action) {
            
            //单独使用HXPhotoPreviewViewController预览图片
            if (self.photoModel.type == HXPhotoModelMediaTypeVideo || self.photoModel.type == HXPhotoModelMediaTypeCameraVideo)
            {
                if (self.photoURL)
                {
                    HXCustomAssetModel *assetModel = [HXCustomAssetModel assetWithLocalVideoURL:self.photoURL selected:YES];
                    [self presentPreviewPhotoController:@[assetModel]];
                }
                else
                {
                    [self showHudWithMessage:@"资源的URL尚未导出成功，请稍后再预览"
                                        mode:MBProgressHUDModeText
                                    autoHide:YES];
                }
            }
            else
            {
                HXCustomAssetModel *assetModel = [HXCustomAssetModel assetWithLocalImage:self.headView.image selected:YES];
                [self presentPreviewPhotoController:@[assetModel]];
            }
        }]];
    }
    else
    {
        [self choosePhoto];
    }
    
}
/** 暂不支持网络视频 */
- (void)previewNetworkVideo
{
    HXCustomAssetModel *assetModel = [HXCustomAssetModel assetWithNetworkImageURL:MSURL(@"https://vd3.bdstatic.com/mda-kg6x4ia0r9psxyag/hd/mda-kg6x4ia0r9psxyag.mp4")
                                                                         selected:YES];
    
    HXWeakSelf
    HXPhotoManager *photoManager = [HXPhotoManager managerWithType:HXPhotoManagerSelectedTypePhotoAndVideo];
    photoManager.configuration.saveSystemAblum = YES;
    photoManager.configuration.photoMaxNum = 0;
    photoManager.configuration.videoMaxNum = 0;
    photoManager.configuration.maxNum = 10;
    photoManager.configuration.selectTogether = YES;
    photoManager.configuration.photoCanEdit = YES;
    photoManager.configuration.videoCanEdit = YES;
    // 添加
    [photoManager addCustomAssetModel:@[assetModel]];

    // 长按事件
    photoManager.configuration.previewRespondsToLongPress = ^(UILongPressGestureRecognizer *longPress,
                                                              HXPhotoModel *photoModel,
                                                              HXPhotoManager *manager,
                                                              HXPhotoPreviewViewController *previewViewController) {
        hx_showAlert(previewViewController, @"提示", @"长按事件", @"确定", nil, nil, nil);
    };
    // 跳转预览界面时动画起始的view
    photoManager.configuration.customPreviewFromView = ^UIView *(NSInteger currentIndex) {
        
        return weakSelf.headView;
    };
    // 跳转预览界面时展现动画的image
    photoManager.configuration.customPreviewFromImage = ^UIImage *(NSInteger currentIndex) {
        
        return weakSelf.headView.image;
    };
    // 退出预览界面时终点view
    photoManager.configuration.customPreviewToView = ^UIView *(NSInteger currentIndex) {
        
        return weakSelf.headView;
    };
    [self hx_presentPreviewPhotoControllerWithManager:photoManager
                                         previewStyle:HXPhotoViewPreViewShowStyleDark
                                         currentIndex:0
                                            photoView:nil];
}

- (void)presentPreviewPhotoController:(NSArray *)assetModels
{
    HXWeakSelf
    HXPhotoManager *photoManager = [HXPhotoManager managerWithType:HXPhotoManagerSelectedTypePhotoAndVideo];
    photoManager.configuration.saveSystemAblum = YES;
    photoManager.configuration.photoMaxNum = 0;
    photoManager.configuration.videoMaxNum = 0;
    photoManager.configuration.maxNum = 10;
    photoManager.configuration.selectTogether = YES;
    photoManager.configuration.photoCanEdit = YES;
    photoManager.configuration.videoCanEdit = YES;

    // 长按事件
    photoManager.configuration.previewRespondsToLongPress = ^(UILongPressGestureRecognizer *longPress,
                                                              HXPhotoModel *photoModel,
                                                              HXPhotoManager *manager,
                                                              HXPhotoPreviewViewController *previewViewController) {
        hx_showAlert(previewViewController, @"提示", @"长按事件", @"确定", nil, nil, nil);
    };
    // 跳转预览界面时动画起始的view
    photoManager.configuration.customPreviewFromView = ^UIView *(NSInteger currentIndex) {
        
        return weakSelf.headView;
    };
    // 跳转预览界面时展现动画的image
    photoManager.configuration.customPreviewFromImage = ^UIImage *(NSInteger currentIndex) {
        
        return weakSelf.headView.image;
    };
    // 退出预览界面时终点view
    photoManager.configuration.customPreviewToView = ^UIView *(NSInteger currentIndex) {
        
        return weakSelf.headView;
    };
    [photoManager addCustomAssetModel:assetModels];

    [self hx_presentPreviewPhotoControllerWithManager:photoManager
                                         previewStyle:HXPhotoViewPreViewShowStyleDark
                                         currentIndex:0
                                         photoView:nil];
}

#pragma mark - HXPhotoViewDelegate

- (void)photoView:(HXPhotoView *)photoView changeComplete:(NSArray<HXPhotoModel *> *)allList photos:(NSArray<HXPhotoModel *> *)photos videos:(NSArray<HXPhotoModel *> *)videos original:(BOOL)isOriginal
{
    if (!ms_arrayIsEmpty(photos))
    {
        HXPhotoModel *photoModel = photos.firstObject;
        [photoModel getImageWithSuccess:^(UIImage * _Nullable image, HXPhotoModel * _Nullable model, NSDictionary * _Nullable info) {
            
            self.headView.image = image;
            self.photoModel = model;
        }
                            failed:^(NSDictionary * _Nullable info, HXPhotoModel * _Nullable model) {
            
            [self showHudWithMessage:@"选取照片失败"
                                mode:MBProgressHUDModeText
                            autoHide:YES];
        }];
    }
    else if (!ms_arrayIsEmpty(videos))
    {
        HXPhotoModel *photoModel = videos.firstObject;
        // 获取当前资源图片
        [photoModel getImageWithSuccess:^(UIImage * _Nullable image, HXPhotoModel * _Nullable model, NSDictionary * _Nullable info) {
            
            self.headView.image = image;
            self.photoModel = model;
        }
                            failed:^(NSDictionary * _Nullable info, HXPhotoModel * _Nullable model) {
            
            [self showHudWithMessage:@"选取照片失败"
                                mode:MBProgressHUDModeText
                            autoHide:YES];
        }];
        
        // 获取当前资源的URL
        [photoModel getAssetURLWithVideoPresetName:AVAssetExportPresetMediumQuality
                                      success:^(NSURL * _Nullable URL, HXPhotoModelMediaSubType mediaType, BOOL isNetwork, HXPhotoModel * _Nullable model) {
            
            // 导出成功
            self.photoURL = URL;
        }
                                       failed:^(NSDictionary * _Nullable info, HXPhotoModel * _Nullable model) {
            // 导出失败
        }];
    }
}


#pragma mark - HXCustomNavigationControllerDelegate
// 通过 HXCustomNavigationControllerDelegate 代理返回选择的图片以及视频
/**
点击完成按钮

@param photoNavigationViewController self
@param allList 已选的所有列表(包含照片、视频)
@param photoList 已选的照片列表
@param videoList 已选的视频列表
@param original 是否原图
*/
- (void)photoNavigationViewController:(HXCustomNavigationController *)photoNavigationViewController didDoneAllList:(NSArray<HXPhotoModel *> *)allList photos:(NSArray<HXPhotoModel *> *)photoList videos:(NSArray<HXPhotoModel *> *)videoList original:(BOOL)original
{
    if (!ms_arrayIsEmpty(photoList))
    {
        HXPhotoModel *photoModel = photoList.firstObject;
        [photoModel getImageWithSuccess:^(UIImage * _Nullable image, HXPhotoModel * _Nullable model, NSDictionary * _Nullable info) {
            
            self.headView.image = image;
            self.photoModel = model;
        }
                            failed:^(NSDictionary * _Nullable info, HXPhotoModel * _Nullable model) {
            
            [self showHudWithMessage:@"选取照片失败"
                                mode:MBProgressHUDModeText
                            autoHide:YES];
        }];
    }
    else if (!ms_arrayIsEmpty(videoList))
    {
        HXPhotoModel *photoModel = videoList.firstObject;
        
        // 获取当前资源图片
        [photoModel getImageWithSuccess:^(UIImage * _Nullable image, HXPhotoModel * _Nullable model, NSDictionary * _Nullable info) {
            
            self.headView.image = image;
            self.photoModel = model;
        }
                            failed:^(NSDictionary * _Nullable info, HXPhotoModel * _Nullable model) {
            
            [self showHudWithMessage:@"选取照片失败"
                                mode:MBProgressHUDModeText
                            autoHide:YES];
        }];
        
        // 获取当前资源的URL
        [photoModel getAssetURLWithVideoPresetName:AVAssetExportPresetMediumQuality
                                      success:^(NSURL * _Nullable URL, HXPhotoModelMediaSubType mediaType, BOOL isNetwork, HXPhotoModel * _Nullable model) {
            
            // 导出成功
            self.photoURL = URL;
        }
                                       failed:^(NSDictionary * _Nullable info, HXPhotoModel * _Nullable model) {
            // 导出失败
        }];
    }
    
}
/**
点击取消

@param photoNavigationViewController self
*/
- (void)photoNavigationViewControllerDidCancel:(HXCustomNavigationController *)photoNavigationViewController
{
    [self showHudWithMessage:@"取消"
                        mode:MBProgressHUDModeText
                    autoHide:YES];
}


#pragma mark - lazy loading

// 懒加载 照片管理类
- (HXPhotoManager *)manager {
    if (!_manager) {
        _manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypePhotoAndVideo];
        _manager.configuration.photoMaxNum = 1;
        _manager.configuration.type = HXConfigurationTypeWXChat;
//        _manager.configuration.limitPhotoSize = 1 * 1024 * 1024;
        _manager.configuration.singleSelected = YES;
        _manager.configuration.lookGifPhoto = NO;
        _manager.configuration.singleJumpEdit = YES;
        _manager.configuration.photoEditConfigur.onlyCliping = YES;
        _manager.configuration.photoEditConfigur.aspectRatio = HXPhotoEditAspectRatioType_Custom;
        _manager.configuration.photoEditConfigur.customAspectRatio = CGSizeMake(1, 1);
    }
    return _manager;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
